<template>
  <div
    class="cl-switch"
    :class="{
      [`cl-switch--${size}`]: size,
      'is-disabled': disabled,
      'is-checked': checked
    }"
    @click="switchValue">
    <input
      class="cl-switch__input"
      type="checkbox"
      role="switch"
      :name="name"
      :disabled="disabled"
      ref="input"
      @keydown.enter="switchValue" />
    <div class="cl-switch__core">
      <div class="cl-switch__core-inner">
        <span
          v-if="activeText || inactiveText"
          class="cl-switch__core-inner-text"
          >{{ checked ? activeText : inactiveText }}</span
        >
      </div>
      <div class="cl-switch__core-action"></div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, onMounted, watch } from 'vue'
import type { SwitchEmits, SwitchProps } from './types'
defineOptions({
  name: 'CLSwitch',
  inheritAttrs: false
})
const props = withDefaults(defineProps<SwitchProps>(), {
  activeValue: true,
  inactiveValue: false
})
const emits = defineEmits<SwitchEmits>()
const input = ref<HTMLInputElement>()
const innerValue = ref(props.modelValue)
const checked = computed(() => innerValue.value === props.activeValue)
const switchValue = () => {
  if (props.disabled) return
  const newValue = checked.value ? props.inactiveValue : props.activeValue
  console.log(newValue)
  innerValue.value = newValue
  emits('update:modelValue', newValue)
  emits('change', newValue)
}
onMounted(() => {
  input.value!.checked = checked.value
})
watch(checked, val => {
  input.value!.checked = val
})
watch(
  () => props.modelValue,
  newValue => {
    innerValue.value = newValue
  }
)
</script>
